import {defZFormFieldCom, } from "../render.js";
import {resolveEventsToTemplate} from "../cm-field-core";
import {baseSelectMixin, createWatchMixin} from "../mixins";


defZFormFieldCom('CusInput', {
  create(propConfig,props,extData) {
    let eventTpl = resolveEventsToTemplate(propConfig)
    let subType = ZY.lodash.get(propConfig, 'ui.widgetConfig.subType')
    let minNum = ZY.lodash.get(propConfig, 'ui.widgetConfig.min')
    // console.log(eventTpl)
    // console.log(props)
    let propType = ZY.lodash.get(propConfig, 'type', '');
    let template = `<el-input v-model="value"
                           :readonly="zfield__readonly"
                           :disabled="zfield__disabled"
            v-on="zfield__listeners"                          
            @input="onInput"
            v-bind="ui.widgetConfig"
            ${eventTpl}
  ></el-input>`
  //   if (propType === 'number') {
  //     template = `<el-input v-model.number="value"
  //                          :readonly="zfield__readonly"
  //                          :disabled="zfield__disabled"
  //           v-on="zfield__listeners"
  //           @input="onInput"
  //           v-bind="ui.widgetConfig"
  //           ${eventTpl}
  // ></el-input>`
  //   }
    let ret = {
      template ,
      data() {
        // console.log(props?.value ?? propConfig?.ui?.widgetConfig?.defaultValue)
        return {
          subType,
          minNum,
          value: undefined,
          rules: propConfig.rules,
          ui: propConfig.ui,
          ...extData,
          needClear: false,
          watchId: ZY.rid()
        }
      },
      created() {
        // let self = this
        // if (typeof self.value === 'undefined') {
        //   self.value = props?.value ?? propConfig?.ui?.widgetConfig?.defaultValue
        // }
        // console.log(self.value)
      },
      mounted() {
        // console.log(this.curFormCon)
        let self = this
        // console.log(self.value)
        if ( self.ui.watch) {
          this.curFormCon.registerHook('afterUpdate', this.watchId, this.detectChange)
        }
      },
      beforeDestroy() {
        this.curFormCon.unRegisterHook('afterUpdate', this.watchId)
      },
      methods: {
        onInput(e) {
          // console.log('onInput', e)
          this.zfield__onInput(e)
        },
        detectChange ({partName, model, s_path, getCmFieldContext, pathArr, e}) {
          if (pathArr.join('') === this.ui.watch.join('')) {
          }
        },
        onKeyUp() {
          // console.log(' this.needClear', this.needClear)
          if ( this.needClear) {
            this.$nextTick(() => {
              this.needClear = false
              // console.log(this.value)
              // this.zfield__setVal(0)
            })
          }
        },
        onKeyDown(e) {
          if (this.subType) {
            if (this.subType === 'integer') {
              let ret = true
              if (e.code === 'Minus') {
                ret = false
              }

              // console.log('onKeyDown', e, ret)
              if (!ret) {
                // e.preventDefault();
                // e.stopPropagation();
                this.needClear = true
              }
            }
          }
        },
        onKeyPress(e) {
          let FLAG = ZY.rid()
          if (this.subType) {
            if (this.subType === 'integer') {
              let ret = (e.charCode === 8 || e.charCode === 0 || e.charCode === 13) ? FLAG : (e.charCode >= 48 && e.charCode <= 57);
              // console.log('onKeyPress', e, ret)
              if (e.code === 'Minus') {
                // ret = true
                if (typeof this.minNum === 'undefined' || this.minNum < 0) {
                  ret = true
                }
              }

              if (!ret) {
                e.preventDefault();
                e.stopPropagation();
              }

            }
          }
          return true
        }
      }
    }
    if (subType === 'integer') {

    }

    return ret
  }
})

defZFormFieldCom('CusInputNumber', {
  create(propConfig, props) {
    return {
      template: `    <el-input-number
          :readonly="zfield__readonly"
          :disabled="zfield__disabled"
          v-model="value"
          @change="onInputNumber"
          controls-position="right"
          v-bind="ui.widgetConfig"></el-input-number>`,
      mixins: [

      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      },
      mounted() {
        // console.log(this.value)
        if (typeof this.value !== 'undefined') {
          this.zfield__onInput(this.value)
        }
      },
      methods:{
        onInputNumber(e) {
          console.log('onInputNumber')
          // let v = parseFloat(e);
          // if (Number.isNaN(v)) {
          //   this.zfield__onInput('')
          // }
          this.zfield__onInput(e)
        }
      }
    }
  }
})

// defZFormFieldCom('CusInputNumber', {
//   create(propConfig) {
//     return {
//       template: `<el-input
//           :readonly="zfield__readonly"
//           :disabled="zfield__disabled"
//           type="number" v-model.number="value"
//         @input="onInputNumber" v-bind="ui.widgetConfig"></el-input>`,
//       mixins: [
//
//       ],
//       data() {
//         return {
//           value: undefined,
//           ui: propConfig.ui,
//         }
//       },
//       methods:{
//         onInputNumber(e) {
//           let v = parseFloat(e);
//           if (Number.isNaN(v)) {
//             this.zfield__onInput('')
//           }
//           this.zfield__onInput(v)
//         }
//       }
//     }
//   }
// })

defZFormFieldCom('CusTextarea', {
  create(propConfig, props) {
    return {
      template: `<div class="cus-textarea-con">${propConfig?.ui?.slots?.afterbegin ?? ''}
      <el-input
          type="textarea"
          :readonly="zfield__readonly"
          :disabled="zfield__disabled"
          v-model="value" @input="zfield__onInput" v-bind="ui.widgetConfig"></el-input>
      ${propConfig?.ui?.slots?.beforeend ?? ''}</div>`,
      mixins: [

      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusCheckSwitch', {
  create(propConfig, props) {
    return {
      template: `
        <el-checkbox
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            true-label='1' false-label='0'
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        ></el-checkbox>
      `,
      mixins: [
      ],
      mounted() {
        if (typeof this.value === 'undefined' || this.value === null) {
          // console.log(this.value)
          this.value = '0'
          this.zfield__onInput(this.value)
        }
      },
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusSwitch', {
  create(propConfig, props) {
    return {
      template: `
        <div class="cus-switch">
        <el-switch
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </el-switch>
        ${propConfig?.ui?.slots?.after ?? ''}
        </div>

      `,
      mixins: [
      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusRate', {
  create(propConfig, props) {
    return {
      template: `
        <el-rate
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </el-rate>`,
      mixins: [
      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusColorPicker', {
  create(propConfig, props) {
    return {
      template: `
        <el-color-picker
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </el-color-picker>
      `,
      mixins: [

      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusSlider', {
  create(propConfig, props) {
    return {
      template: `
        <el-slider
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </el-slider>
      `,
      mixins: [

      ],
      data() {
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
})

defZFormFieldCom('CusDatePicker', {
  create(propConfig, props) {
    // console.log(propConfig)
    return {
      template: `
        <ex-date-picker
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </ex-date-picker>`,
      data() {
        let w = propConfig.ui.widgetConfig;
        w.valueFormat = 'yyyy-MM-dd HH:mm:ss'
        // console.log(w)
        return {
          widgetConfig: w,
          value: props?.value,
          ui: propConfig.ui,
        }
      },
    }
  }
});

defZFormFieldCom('CusDateTimePicker', {
  create(propConfig, props) {
    // console.log(propConfig)
    return {
      template: `
        <ex-date-picker
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            type="datetime"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </ex-date-picker>`,
      data() {
        let w = propConfig?.ui?.widgetConfig;
        if (w && !w.valueFormat) {
          w.valueFormat = 'yyyy-MM-dd HH:mm:ss';
        }
        // console.log(w)
        return {
          widgetConfig: w,
          value: props?.value,
          ui: propConfig.ui,
        }
      },
    }
  }
});

defZFormFieldCom('CusTimePicker', {
  create(propConfig, props) {
    // console.log(propConfig)
    return {
      template: `
        <ex-time-picker
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
        >
        </ex-time-picker>`,
      mixins: [

      ],
      data() {
        let w = propConfig?.ui?.widgetConfig;
        if (w && !w.valueFormat) {
          w.valueFormat = 'HH:mm:ss';
        }
        return {
          value: props?.value,
          ui: propConfig.ui,
        }
      }
    }
  }
});


defZFormFieldCom('CusCheckbox', {
  create(propConfig, props) {
    return {
      template: `
        <div class="cus-checkbox-con">
          <template v-if="zfield__readonly">
            <template v-if="value">{{value.join()}}</template>
          </template>
          <template v-else>
            <el-checkbox-group
                :readonly="zfield__readonly"
                :disabled="zfield__disabled"
                v-model="value"
                @change="zfield__onInput"
                v-bind="ui.widgetConfig"
            >
              <el-checkbox v-for="(option, key) in zfeild__buildOptions(ui, reqOptions)"
                           :label="option.value"
              >{{option.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
      `,
      mixins: [
        baseSelectMixin
      ],
      data() {
        return {
          ui: propConfig.ui,
          value: props?.value ?? [],
        }
      },
      async created() {
        await this.initDataSource()
      },
      // beforeCreate() {
      //   console.log(this.value)
      // },
      methods: {

      }
    }
  }
})

defZFormFieldCom('CusRadio', {
  create(propConfig, props) {
    return {
      template: `
        <div class="cus-radio-con">
          <template v-if="zfield__readonly">
            {{value}}
          </template>
           <template v-else>
             <el-radio-group
                 :readonly="zfield__readonly"
                 :disabled="zfield__disabled"
                 v-model="value"
                 @change="zfield__onInput"
                 v-bind="ui.widgetConfig"
             >
               <el-radio v-for="(option, key) in zfeild__buildOptions(ui, reqOptions)"
                         :label="option.value"
               >{{option.label}}</el-radio>
             </el-radio-group>
           </template> 
        </div>
      `,
      mixins: [
        baseSelectMixin
      ],
      data() {
        return {
          ui: propConfig.ui,
          value: props?.value ,
        }
      },
      async created() {
        await this.initDataSource()
      },
      methods: {

      }
    }
  }
});

defZFormFieldCom('CusSelect', {
  create(propConfig,props,extData) {
    let watchMixin = createWatchMixin(propConfig, props)
    return {
      template: `
        <div class="cus-select-con">
          <template v-if="zfield__readonly">
            {{value}}
          </template>
          <template v-else>
            <el-select
                :readonly="zfield__readonly"
                :disabled="zfield__disabled"
                v-model="value"
                @change="onSelectChange"
                v-bind="ui.widgetConfig"
            >
              <el-option v-for="(option, key) in zfeild__buildOptions(ui, reqOptions)"
                         :label="option.label"
                         :value="option.value"
              ></el-option>
            </el-select>
          </template>
        </div>
      `,
      mixins: [
        baseSelectMixin,
        watchMixin
      ],
      data() {
        return {
          ui: propConfig.ui,
          propConfig,
          value: props?.value ,
        }
      },
      async created() {
        // let self = this;
        // // console.log(this.zfield__highConfig)
        // await this.zfield__initDataSource({
        //   onRequest(apiConfig) {
        //     self.onRequest(apiConfig)
        //   }
        // })
        let canAutoUpload = await this.installWatchUpdate();
        // console.log(canAutoUpload)
        await ZY.sleep(100);
        if (canAutoUpload) {
          await this.initDataSource()
        }
      },
      beforeUnMount() {
        this.unInstallWatchUpdate()
      },
      methods: {
        getOptions() {
          return this.zfeild__buildOptions(this.ui, this.reqOptions)
        },
        getCurOption() {
          let options = this.getOptions();
          if (Array.isArray(options)) {
            let option = options.find(v => {
              return v.value === this.value
            });
            return option
          }
        },
        async initOptions() {
          let self = this
          let zFormMeta = globalThis.ZForm.getZFormMeta(this)
          let api = ZY.lodash.get(this.ui, 'widgetConfig.api')
          if (api) {
            // console.log(api)
            this.reqOptions = await this.zfield__req(zFormMeta,{
              event: 'init:options',
              options: {
                api,
                propConfig: self.propConfig,
                props
              }
            })
            // console.log(this.reqOptions)
          }
        },
        reloadOptions(arr = []) {
          // this.zfield__onInput('')
          // this.value = ''
          this.reqOptions = [].concat(arr)
        },
        reloadOptionsAndSelectFirst(arr = []) {
          this.reloadOptions(arr)
          if (arr[0]) {
            this.zfield__setAndUpdate(arr[0].value)
          }
        },
        async reloadDataSourceAndSelectFirst() {
          let options = await this.reloadDataSource()
          await ZY.sleep(100)
          let arr = options
          if (arr[0]) {
            this.zfield__setAndUpdate(arr[0].value)
          }
        },
        onSelectChange(v) {
          // let zFormMeta = globalThis.ZForm.getZFormMeta(this)
          // // console.log(zFormMeta)
          // if (zFormMeta?.events && zFormMeta.events['select:change']) {
          //   zFormMeta?.events['select:change']({
          //     value: v, self_path: props.self_path, props, curFormCon: this.curFormCon});
          // }
          this.zfield__emit('com:select:change', {
            value: v
          })
          this.zfield__onInput(v)
        }
      }
    }
  }
});

defZFormFieldCom('CusCascader', {
  create(propConfig, props) {
    return {
      template: `
        <el-cascader
            :readonly="zfield__readonly"
            :disabled="zfield__disabled"
            v-model="value"
            @change="zfield__onInput"
            v-bind="ui.widgetConfig"
            :options="zfeild__buildOptions(ui)"
        >
        </el-cascader>
      `,
      mixins: [

      ],
      data() {
        return {
          ui: propConfig.ui,
          value: props?.value ,
        }
      },
      methods: {
        getOptions() {
          return this.zfeild__buildOptions(this.ui)
        }
      }
    }
  }
})

defZFormFieldCom('CusSimpleUploader', {
  create(propConfig, props) {
    return {
      template: `
        <z-upload
            v-model="value"
            @change="zfield__onInput"
            button-txt="上传"
            :action="ui.widgetConfig.action"
            :binds="ui.widgetConfig"
        >
        </z-upload>
      `,
      mixins: [

      ],
      data() {
        return {
          ui: propConfig.ui,
          value: props?.value ,
        }
      },

      methods: {

      }
    }
  }
})

defZFormFieldCom('CusUploader', {
  create(propConfig, props) {
    return {
      template: `
        <z-upload
            v-model="value"
            @change="zfield__onInput"
            button-txt="上传"
            :action="ui.widgetConfig.action"
            :binds="ui.widgetConfig"
        >
        </z-upload>
      `,
      mixins: [

      ],
      data() {
        // console.log(propConfig)
        if (!propConfig.ui) {
          propConfig.ui = {}
        }
        if (!propConfig.ui.widgetConfig) {
          propConfig.ui.widgetConfig = {}
        }
        if (propConfig.action) {
          propConfig.ui.widgetConfig.action = propConfig.action
        }
        return {
          ui: propConfig.ui,
          value: props?.value,
        }
      },

      methods: {

      }
    }
  }
})

defZFormFieldCom('CusImgUploader', {
  create(propConfig, props) {
    return {
      template: `
        <z-upload
            v-model="value"
            @change="zfield__onInput"
            button-txt="上传"
            :action="ui.widgetConfig.action"
            :binds="ui.widgetConfig"
        >
        </z-upload>
      `,
      mixins: [

      ],
      data() {
        if (!propConfig.ui) {
          propConfig.ui = {}
        }
        if (!propConfig.ui.widgetConfig) {
          propConfig.ui.widgetConfig = {}
        }
        propConfig.ui.widgetConfig['list-type'] = 'picture-card'
        return {
          ui: propConfig.ui,
          value: props?.value,
        }
      },

      methods: {

      }
    }
  }
})


